package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.XYCreditEaseService;
import com.meirengu.utils.HttpUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwThirdback;
import com.meirengu.webview.service.KwThirdbackService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 西伊宜信
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class XYCreditEaseServiceImpl implements XYCreditEaseService {

    Logger logger = LoggerFactory.getLogger(XYCreditEaseServiceImpl.class);
    @Autowired
    KwThirdbackService kwThirdbackService;

    /**
     * @param
     * @return
     */

    public Integer applyLoan(String name, String sex, String mobile, String birthDate,
                             String city, String loan, String hasHouse, String hasCar,
                             String job, String salaryPayType, String salary,
                             String socialInsurance, String houseInsurance,
                             String jobTime, String insurance) throws Exception {

        String url = ConfigUtil.getConfig("xy.creditease.url");
        String uid = ConfigUtil.getConfig("xy.creditease.uid");
        String token = ConfigUtil.getConfig("xy.creditease.token");
        url = url + "?uid=" + uid + "&token=" + token;


        JSONObject userJson = new JSONObject();
        userJson.put("productType", 2);
        userJson.put("name", name);//客户姓名
        userJson.put("sex", sex);//性别  0:男 1：女
        userJson.put("mobile", mobile);//手机号
        /*userJson.put("qq", QQ);//QQ
        userJson.put("email", email);//邮箱
        userJson.put("identityNumber", identityNumber);//身份证号*/
        userJson.put("birthDate", birthDate);//出生日期
        /*userJson.put("provice", provice);//省份*/
        userJson.put("city", city);//城市
        userJson.put("loan", loan);//期望贷款金额
        /*userJson.put("loanTime", loanTime);//借款周期
        userJson.put("registered", registered);//户籍地*/
        userJson.put("hasHouse", hasHouse);//名下房产  0：无房产 1：有房产，还贷中 2：有房产，无房贷
        userJson.put("hasCar", hasCar);//名下车辆  0：无汽车 1：有汽车，还贷中 2：有房产，无车贷
        userJson.put("job", job);//职业  0：上班族 1：公务员 2：私营业主
        userJson.put("salaryPayType", salaryPayType);//薪资发放形式 0：银行卡发放 1：现金发放
        userJson.put("salary", salary);//薪水
        userJson.put("socialInsurance", socialInsurance);//社保公积金  0：缴费未满一年 1：缴费一年以上 2：无社保
        userJson.put("houseInsurance", houseInsurance);//住房公积金  0：无 1：有
        userJson.put("jobTime", jobTime);//工作时间  0：现单位6个月以内 1：现单位6-12个月 2：现单位12-24个月 3：现单位24个月以上
        /*userJson.put("businessLicense", businessLicense);//营业执照  0：无 1：有*/
        userJson.put("insurance", insurance);//人寿保险单  0：无 1：有，年缴费2400元以下 2：有，年缴费2400元以上
        /*userJson.put("hasWeilidai", hasWeilidai);//微粒贷  0：无 1：有*/
        JSONArray importListJson = new JSONArray();
        importListJson.add(userJson);


        //接口调用信息表
        KwThirdback thirdback = new KwThirdback();
        thirdback.setInterfaceCode("xycreditease");
        thirdback.setInterfaceName("西伊宜信");
        thirdback.setMobile(mobile);
        thirdback.setSendUrl(url.toString());
        thirdback.setParams(importListJson.toString());
        thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);

        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPost(url, importListJson.toString());
            int code = hr.getStatusCode();
            if (code == 200) {
                thirdback.setBackUrl(hr.toString());
                thirdback.setHttpCode(200);
                thirdback.setHttpContent(hr.toString());

                logger.info("==XYCreditEaseServiceImpl.applyLoan request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("code");
                String rMsg = returnMsg.getString("msg");
                if ("0".equals(rCode)) {
                    JSONArray retArray = returnMsg.getJSONArray("ret");
                    for (int i = 0; i < retArray.size(); i++) {
                        JSONObject jsonObject = retArray.getJSONObject(i);
                        boolean succ = jsonObject.getBoolean("succ");
                        if (succ) {
                            thirdback.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                            thirdback.setMessage("成功");
                            logger.info("==XYCreditEaseServiceImpl.applyLoan business success");
                        } else {
                            thirdback.setCode(Constants.BUSINESS_STATUS_OTHER);
                            thirdback.setMessage("rCode: " + succ + " rMsg:" + jsonObject.getString("msg"));
                            logger.warn("==XYCreditEaseServiceImpl.applyLoan business fail");
                        }
                    }
                } else {
                    thirdback.setCode(Constants.BUSINESS_STATUS_OTHER);
                    thirdback.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==XYCreditEaseServiceImpl.applyLoan business fail");
                }
            } else {
                thirdback.setBackUrl(hr.toString());
                thirdback.setHttpCode(code);
                thirdback.setHttpContent(hr.toString());
                logger.warn("==XYCreditEaseServiceImpl.applyLoan request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            thirdback.setHttpCode(408);
            thirdback.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwThirdbackService.insert(thirdback);
            return thirdback.getCode();
        }
    }

}
